export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.directive("click-move", {
    mounted(el: HTMLElement) {
      if (!import.meta.client) return;
      let isAnimating = false;
      let resetTimeout: ReturnType<typeof setTimeout> | null = null;
      let finishTimeout: ReturnType<typeof setTimeout> | null = null;

      const clearTimers = () => {
        if (resetTimeout) clearTimeout(resetTimeout);
        if (finishTimeout) clearTimeout(finishTimeout);
        resetTimeout = null;
        finishTimeout = null;
        (el as any)._clickMoveResetTimeout = null;
        (el as any)._clickMoveFinishTimeout = null;
      };

      const reset = () => {
        el.style.transition = "";
        el.style.transform = "translateY(0)";
      };

      const startAnimation = () => {
        isAnimating = true;
        // 下沉
        el.style.transition =
          "transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)";
        el.style.transform = "translateY(0.15rem)";
        // 回弹
        resetTimeout = setTimeout(() => {
          el.style.transform = "translateY(0)";
          (el as any)._clickMoveResetTimeout = resetTimeout;
          finishTimeout = setTimeout(() => {
            isAnimating = false;
            el.style.transition = "";
          }, 300);
          (el as any)._clickMoveFinishTimeout = finishTimeout;
        }, 150);
        (el as any)._clickMoveResetTimeout = resetTimeout;
      };

      const handleClick = () => {
        // 若正在动画：立即回到初始状态并重新开始
        if (isAnimating) {
          clearTimers();
          reset();
          isAnimating = false;
        }
        // 强制回到初始状态（无过渡）
        el.style.transition = "";
        el.style.transform = "translateY(0)";
        // 强制 reflow 保证下一次动画从初始值开始
        void el.offsetWidth;
        // 使用 rAF 确保样式写入顺序
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            startAnimation();
          });
        });
      };

      el.addEventListener("click", handleClick);
      // 保存引用以便清理
      (el as any)._clickHandler = handleClick;
      (el as any)._clickMoveResetTimeout = resetTimeout;
      (el as any)._clickMoveFinishTimeout = finishTimeout;
    },
    unmounted(el: HTMLElement) {
      if (!import.meta.client) return;
      if ((el as any)._clickHandler) {
        el.removeEventListener("click", (el as any)._clickHandler);
      }
      if ((el as any)._clickMoveResetTimeout) {
        clearTimeout((el as any)._clickMoveResetTimeout);
      }
      if ((el as any)._clickMoveFinishTimeout) {
        clearTimeout((el as any)._clickMoveFinishTimeout);
      }
    },
  });
});
